package com.lihua.project.taskcenter.taskcenter.controller;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.lihua.common.utils.CacheUtils;
import com.lihua.framework.websocket.session.WsSession;
import com.lihua.project.system.chat.domain.Chat;
import com.lihua.project.system.chat.service.IChatService;
import com.lihua.project.system.user.domain.PublicUser;
import com.lihua.project.system.user.domain.User;
import com.lihua.project.system.user.service.IUserService;
import com.lihua.project.system.score.domain.TsScore;
import com.lihua.project.system.score.service.ITsScoreService;
import com.lihua.project.system.user.utils.GradeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lihua.framework.aspectj.lang.annotation.Log;
import com.lihua.framework.aspectj.lang.enums.BusinessType;
import com.lihua.project.taskcenter.taskcenter.domain.Task;
import com.lihua.project.taskcenter.taskcenter.service.ITaskService;
import com.lihua.framework.web.controller.BaseController;
import com.lihua.framework.web.domain.AjaxResult;
import com.lihua.common.utils.poi.ExcelUtil;
import com.lihua.framework.web.page.TableDataInfo;

import javax.websocket.Session;

/**
 * 任务Controller
 *
 * @author lihua
 * @date 2022-03-08
 */
@Controller
@RequestMapping("/taskcenter/taskcenter")
@Slf4j
public class TaskController extends BaseController {
    private String prefix = "taskcenter/taskcenter";

    /**评分时间，默认7天*/
    private static final long SCORING_TIME = 7*24*60*60*1000;

    @Autowired
    private IChatService chatService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ITsScoreService tsScoreService;

    @RequiresPermissions("taskcenter:taskcenter:view")
    @GetMapping()
    public String taskcenter() {
        return prefix + "/taskcenter";
    }


    @GetMapping("/index")
    public String taskcenterIndex() {
        return prefix + "/taskcenter-index";
    }

    /**
     * 查询任务列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Task task) {
        startPage();
        List<Task> list = taskService.selectTaskList(task);
        return getDataTable(list);
    }

    /**
     * 根据用户id查询任务列表
     */
    @PostMapping("/user/list")
    @ResponseBody
    public TableDataInfo listByUserId(Task task) {
        //如果userId为null，默认查询用户自己的数据
        if (task.getUserId()==null){
            User user = getSysUser();
            task.setUserId(user.getUserId());
        }
        startPage();
        List<Task> list = taskService.selectTaskList(task);
        return getDataTable(list);
    }

    /**
     * 导出任务列表
     */
    @RequiresPermissions("taskcenter:taskcenter:export")
    @Log(title = "任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Task task) {
        List<Task> list = taskService.selectTaskList(task);
        ExcelUtil<Task> util = new ExcelUtil<Task>(Task.class);
        return util.exportExcel(list, "任务数据");
    }

    /**
     * 新增任务
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 首页新增任务
     */
    @GetMapping("/addIndex")
    public String addIndex() {
        return prefix + "/index-add";
    }

    /**
     * 新增保存任务
     */
    @RequiresPermissions("taskcenter:taskcenter:add")
    @Log(title = "任务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Task task) {
        return toAjax(taskService.insertTask(task));
    }

    /**
     * 修改任务视图
     */
    @RequiresPermissions("taskcenter:taskcenter:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        Task task = taskService.selectTaskById(id);
        mmap.put("task", task);
        return prefix + "/edit";
    }

    /**
     * 修改保存任务
     */
    @RequiresPermissions("taskcenter:taskcenter:edit")
    @Log(title = "任务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Task task) {
        return toAjax(taskService.updateTask(task));
    }


    /**
     * 更换匹配任务保存任务
     */
    @RequiresPermissions("taskcenter:taskcenter:edit")
    @Log(title = "任务", businessType = BusinessType.UPDATE)
    @PostMapping("/replaceTask")
    @ResponseBody
    public AjaxResult replaceTask(Task task) {
        return toAjax(taskService.replaceTask(task));
    }

    /**
     * 修改任务匹配状态
     */
    @RequiresPermissions("taskcenter:taskcenter:edit")
    @Log(title = "任务匹配状态", businessType = BusinessType.UPDATE)
    @PostMapping("/edit/matchStatus")
    @ResponseBody
    public AjaxResult editMatchStatusSave(Task task) {
        return toAjax(taskService.updateTaskMatchStatus(task));
    }

    /**
     * 删除任务
     */
    @RequiresPermissions("taskcenter:taskcenter:remove")
    @Log(title = "任务", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(taskService.deleteTaskByIds(ids));
    }


    /**
     * 查询详细方法
     */
    @GetMapping("/detail/{taskId}")
    @RequiresPermissions("taskcenter:taskcenter:detail")
    public String detail(@PathVariable("taskId") Long taskId, ModelMap mmap) {
        Task task = taskService.selectTaskById(taskId);
        mmap.put("taskDetail", task);
        //获取本任务的发布者的用户信息
        Long userId = task.getUserId();
        User user = userService.selectUserById(userId);
        PublicUser selfUser = user.getPublicUser(user);
        mmap.put("selfUser", selfUser);
        //获取关联任务的任务信息
        Long taskLinkId = task.getTaskLinkId();
        //当前匹配数
        mmap.put("taskMatchSize", CacheUtils.get("taskCache", "taskMatchSize"));
        //如果taskLinkId等于null 或者 等于-1表示任务没有匹配成功
        if (taskLinkId != null && taskLinkId != -1) {
            //连接的任务
            Task linkTask = taskService.selectTaskById(taskLinkId);
            if (linkTask != null) {
                mmap.put("linkTask", linkTask);
                //获取关联任务的用户信息
                Long linkUserId = linkTask.getUserId();
                User linkUser1 = userService.selectUserById(linkUserId);
                PublicUser linkUser = user.getPublicUser(linkUser1);
                mmap.put("linkUser", linkUser);

                //如果任务进行中，查询聊天模块中对方的在线状态
                if ("3".equals(task.getStatus())||"4".equals(task.getStatus())){
                    Session session = WsSession.getSession(linkUserId.toString());
                    if (session==null){
                        //不在线
                        mmap.put("onlineStatus","0");
                    } else {
                        mmap.put("onlineStatus","1");
                    }
                    //获取用户自己的未读消息
                    Chat chat = new Chat();
                    String chatId = userId<linkUserId?userId+"-"+linkUserId:linkUserId+"-"+userId;
                    chat.setChatId(chatId);
                    chat.setUserId(linkUserId);
                    chat.setMsgState("0");
                    List<Chat> chats = chatService.selectChatList(chat);
                    if (chats!=null){
                        mmap.put("unreadSize",chats.size());
                        if (chats.size()>0){
                            mmap.put("newestUnread",chats.get(chats.size()-1));
                        }else {
                            //直接取一条最新的历史消息
                            chat.setMsgState(null);
                            PageHelper.startPage(1, 1, "create_time desc").setReasonable(true);
                            List<Chat> historyChats = chatService.selectChatList(chat);
                            if (historyChats.size()>0){
                                mmap.put("unreadSize",0);
                                mmap.put("newestUnread",historyChats.get(0));
                            }else {
                                mmap.put("unreadSize",0);
                                mmap.put("newestUnread",new Chat());
                            }
                        }
                    } else {
                        mmap.put("unreadSize",0);
                        mmap.put("newestUnread",new Chat());
                    }
                }

                //判断任务是否结束
                long finishDate = task.getFinishDate().getTime();
                long finishDateLink = linkTask.getFinishDate().getTime();
                //任务截至时间到后，进入评分阶段，默认7天
                if (System.currentTimeMillis()>finishDate){
                    //修改任务状态
                    if (task.getStatus().equals("3")){
                        Task task1 = new Task();
                        task1.setStatus("4");
                        task1.setId(task.getId());
                        taskService.updateTask(task1);
                    }
                }
                if (System.currentTimeMillis()>finishDateLink){
                    //修改任务状态
                    if (linkTask.getStatus().equals("3")){
                        Task task1 = new Task();
                        task1.setStatus("4");
                        task1.setId(linkTask.getId());
                        taskService.updateTask(task1);
                    }
                }


                //任务结束后有7天的评分时间，七天后任务自动结束，并进行任务结算
                if (System.currentTimeMillis()>finishDate+SCORING_TIME && System.currentTimeMillis()>finishDateLink+SCORING_TIME){
                    //修改任务状态
                    if (task.getStatus().equals("4")){
                        //计算总分 ,修改任务状态
                        TsScore tsScore = new TsScore();
                        tsScore.setTaskId(task.getId());
                        List<TsScore> tsScores = tsScoreService.selectTsScoreList(tsScore);
                        double totalScore =0;
                        for (TsScore score : tsScores) {
                            totalScore =totalScore + score.getScore();
                        }
                        if (totalScore==0){
                            totalScore = 10.0;
                        } else {
                            totalScore = totalScore/3;

                            totalScore = Double.parseDouble(String.format("%.2f",totalScore));
                        }

                        Task task1 = new Task();
                        task1.setStatus("5");
                        task1.setScore(totalScore);
                        task1.setId(task.getId());
                        taskService.updateTask(task1);

                        //为用户增加自律积分,积分计算规则。每个任务的评分*5(也就是一个任务最多50分)
                        double integralAdd = totalScore*5;
                        //判断增加经验后能否升级
                        //目前的总积分
                        double integralOld = user.getIntegral();
                        double integralNow = integralOld+integralAdd;
                        //当前等级
                        Long grade = user.getGrade();
                        if (integralNow>GradeUtils.getExperience(grade+1)){
                            //能升级
                            grade = grade+1;
                        }
                        //更新user信息
                        User user1 = new User();
                        user1.setUserId(task.getUserId());
                        user1.setIntegral(integralNow);
                        user1.setGrade(grade);
                        userService.updateUser(user1);

                    }
                    if (linkTask.getStatus().equals("4")){
                        //计算总分 ,修改任务状态
                        TsScore tsScore = new TsScore();
                        tsScore.setTaskId(linkTask.getId());
                        List<TsScore> tsScores = tsScoreService.selectTsScoreList(tsScore);
                        double totalScore =0;
                        for (TsScore score : tsScores) {
                            totalScore =(totalScore + score.getScore())/3;
                        }

                        Task task1 = new Task();
                        task1.setStatus("5");
                        task1.setScore(totalScore);
                        task1.setId(linkTask.getId());
                        taskService.updateTask(task1);

                        //为用户增加自律积分,积分计算规则。每个任务的评分*5(也就是一个任务最多50分)
                        double integralAdd = totalScore*5;
                        //判断增加经验后能否升级
                        //目前的总积分
                        double integralOld = linkUser.getIntegral();
                        double integralNow = integralOld+integralAdd;
                        //当前等级
                        Long grade = linkUser.getGrade();
                        if (integralNow>GradeUtils.getExperience(grade+1)){
                            //能升级
                            grade = grade+1;
                        }
                        //更新user信息
                        User user1 = new User();
                        user1.setUserId(linkUser.getUserId());
                        user1.setIntegral(integralNow);
                        user1.setGrade(grade);
                        userService.updateUser(user1);
                    }
                    //1表示已结束
                    mmap.put("taskFinish","1");
                    //2、计算任务历时
                    long duration = task.getFinishDate().getTime()-task.getCreateTime().getTime();
                    long durationDay = duration/(1000*60*60*24);
                    mmap.put("durationDay",durationDay);
                }else {
                    mmap.put("taskFinish","0");
                }

            } else {
                //关联任务不存在，可能已删除
                mmap.put("linkTask", null);
            }
        } else {
            mmap.put("linkTask", null);
        }
        //查询评分
        if("3".equals(task.getStatus())||"4".equals(task.getStatus())||"5".equals(task.getStatus())){
            TsScore tsScore = new TsScore();
            tsScore.setTaskId(task.getTaskLinkId());
            //关联任务的评分
            List<TsScore> tsScores = tsScoreService.selectTsScoreList(tsScore);
            Iterator<TsScore> iterator = tsScores.iterator();
            while (iterator.hasNext()){
                TsScore score = iterator.next();
                if (System.currentTimeMillis()-score.getStartTime().getTime()<0){
                    iterator.remove();
                }
            }
            mmap.put("linkTaskScores", tsScores);
            //自己的评分标准
            tsScore.setTaskId(task.getId());
            List<TsScore> tsScores1 = tsScoreService.selectTsScoreList(tsScore);
            Iterator<TsScore> iterator1 = tsScores1.iterator();
            while (iterator1.hasNext()){
                TsScore score1 = iterator1.next();
                if (System.currentTimeMillis()-score1.getBeginTime().getTime()<0){
                    iterator1.remove();
                }

            }
            mmap.put("scores", tsScores1);
        }

        return prefix + "/detail";
    }

    /**
     * 查询详细方法——只有查看权限
     */
    @GetMapping("/detail/public/{taskId}")
    public String detailView(@PathVariable("taskId") Long taskId, ModelMap mmap) {
        Task task = taskService.selectTaskById(taskId);
        mmap.put("taskDetail", task);
        //获取本任务的发布者的用户信息
        Long userId = task.getUserId();
        User user = userService.selectUserById(userId);
        PublicUser selfUser = user.getPublicUser(getSysUser());
        //登录的用户
        mmap.put("selfUser", selfUser);
        //这个任务的用户
        mmap.put("user", user);
        //获取关联任务的任务信息
        Long taskLinkId = task.getTaskLinkId();
        //当前匹配数
        mmap.put("taskMatchSize", CacheUtils.get("taskCache", "taskMatchSize"));
        //如果taskLinkId等于null 或者 等于-1表示任务没有匹配成功
        if (taskLinkId != null && taskLinkId != -1) {
            //连接的任务
            Task linkTask = taskService.selectTaskById(taskLinkId);
            if (linkTask != null) {
                mmap.put("linkTask", linkTask);
                //获取关联任务的用户信息
                Long linkUserId = linkTask.getUserId();
                User linkUser1 = userService.selectUserById(linkUserId);
                PublicUser linkUser = user.getPublicUser(linkUser1);
                mmap.put("linkUser", linkUser);
                //判断任务是否结束
                long finishDate = task.getFinishDate().getTime();
                long finishDateLink = linkTask.getFinishDate().getTime();
                //任务截至时间到后，进入评分阶段，默认7天
                if (System.currentTimeMillis()>finishDate){
                    //修改任务状态
                    if (task.getStatus().equals("3")){
                        Task task1 = new Task();
                        task1.setStatus("4");
                        task1.setId(task.getId());
                        taskService.updateTask(task1);
                    }
                }
                if (System.currentTimeMillis()>finishDateLink){
                    //修改任务状态
                    if (linkTask.getStatus().equals("3")){
                        Task task1 = new Task();
                        task1.setStatus("4");
                        task1.setId(linkTask.getId());
                        taskService.updateTask(task1);
                    }
                }


                //任务结束后有7天的评分时间，七天后任务自动结束
                if (System.currentTimeMillis()>finishDate+SCORING_TIME && System.currentTimeMillis()>finishDateLink+SCORING_TIME){
                    //修改任务状态
                    if (task.getStatus().equals("4")){
                        Task task1 = new Task();
                        task1.setStatus("5");
                        task1.setId(task.getId());
                        taskService.updateTask(task1);
                    }
                    if (linkTask.getStatus().equals("4")){
                        Task task1 = new Task();
                        task1.setStatus("5");
                        task1.setId(linkTask.getId());
                        taskService.updateTask(task1);
                    }
                }
            } else {
                //关联任务不存在，可能已删除
                mmap.put("linkTask", null);
            }
        } else {
            mmap.put("linkTask", null);
        }
        return prefix + "/detail-public";
    }

    @GetMapping("/chat/{userId}/{otherSideUserId}")
    public String goChat(@PathVariable("userId") String userId,@PathVariable("otherSideUserId")  String otherSideUserId,ModelMap mmap){
        mmap.put("userId",userId);
        mmap.put("otherSideUserId",otherSideUserId);
        //获取用户名和头像
        User user = getSysUser();
        mmap.put("userName",user.getUserName()==null?user.getLoginName():user.getUserName());
        mmap.put("avatar",user.getAvatar());

        //获取聊天对象的用户名
        User linkUser = userService.selectUserById(Long.parseLong(otherSideUserId));
        mmap.put("linkUserName",linkUser.getUserName()==null?linkUser.getLoginName():linkUser.getUserName());
        //获取聊天对象的在线状态
        Session session = WsSession.getSession(otherSideUserId);
        if (session==null){
            //不在线
            mmap.put("onlineStatus","0");
        } else {
            mmap.put("onlineStatus","1");
        }
        //获取历史数据
        Chat chat = new Chat();
        //chatId唯一标记一个聊天
        String chatId = Long.parseLong(userId)<Long.parseLong(otherSideUserId)?userId+"-"+otherSideUserId:otherSideUserId+"-"+userId;
        chat.setChatId(chatId);
        PageHelper.startPage(1, 5, "create_time desc").setReasonable(true);
        List<Chat> historyChats = chatService.selectChatList(chat);
        TableDataInfo dataTable = getDataTable(historyChats);
        mmap.put("dataTable",dataTable);
        //将未读的消息改为已读
        if (historyChats!=null){
            for (Chat historyChat : historyChats) {
                //将自己未读的消息设置为已读
                if (historyChat.getMsgState().equals("0")&&historyChat.getUserId()==Long.parseLong(otherSideUserId)){
                    historyChat.setMsgState("1");
                    chatService.updateChat(historyChat);
                }
            }
        }

        return "chat/room";
    }
}
